<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                        <el-form-item label="车间" prop="factoryId" label-width="40px">
                            <el-select v-model="queryParams.factoryId" placeholder="请选择车间" clearable style="width: 150px;">
                                <el-option
                                        v-for="dict in factoryIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="车间区域" prop="factoryAreaId">
                            <el-select v-model="queryParams.factoryAreaId" placeholder="请选择车间区域" clearable @change="areaChange" style="width: 150px;">
                                <el-option
                                        v-for="dict in factoryAreaIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="制造类型" prop="productionTypeId">
                            <el-select v-model="queryParams.productionTypeId" placeholder="请选择制造类型" @change="productionTypeIdChange" clearable style="width: 150px;">
                                <el-option
                                        v-for="dict in listProductionTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="设备类型" prop="machineTypeId">
                            <el-select v-model="queryParams.machineTypeId" placeholder="请选择设备类型" clearable style="width: 150px;">
                                <el-option
                                        v-for="dict in listMachineTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['funConfig:stInfo:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['funConfig:stInfo:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['funConfig:stInfo:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['funConfig:stInfo:export']"
                >导出</el-button>
            </el-col>

            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @update:showSearch="showSearch ? height = 'calc(100% - 100px)' : height = 'calc(100% - 62px)'">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </right-toolbar>
        </el-row>

        <t-ag-grid
            :style="{height: height}"
            :column-defs="column"
            :row-data="tableData"
            :row-buffer="20"
            row-selection="multiple"
            :suppress-row-click-selection="true"
            :row-multi-select-with-click="true"
            align="center"
            :defaultColDef = "{
                // suppressMenu:true
                menuTabs: ['filterMenuTab', 'columnsMenuTab']
            }"
            header-align="center"
            @selection-changed="selectionChanged"
            />
            <!-- :getMainMenuItems="getMainMenuItems" -->
            <!-- @getSelectedRows="selectionChanged" -->

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改AST_ST基准情报对话框 -->
        <el-dialog :title="title" v-model="open" width="550px" append-to-body>
            <el-form ref="stInfoRef" :model="form" :inline="true" :rules="rules" label-width="80px">
                                <!-- <el-form-item label="车间" prop="factoryId">
                                    <el-select v-model="form.factoryId" placeholder="请选择车间" clearable style="width: 150px;">
                                    <el-option
                                        v-for="dict in factoryIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                    />
                                </el-select>
                                </el-form-item> -->
                                <el-form-item label="车间区域" prop="factoryAreaId">
                                    <el-select v-model="form.factoryAreaId" placeholder="请选择车间区域" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in factoryAreaIdOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="制造类型" prop="productionTypeId">
                                    <el-select v-model="form.productionTypeId" placeholder="请选择制造类型" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in listProductionTypeOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                </el-form-item>

                                <el-form-item label="设备类型" prop="machineTypeId">
                                    <el-select v-model="form.machineTypeId" placeholder="请选择设备类型" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in listMachineTypeOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="设备ID" prop="machineId">
                                    <el-input :disabled="title.includes('修改')" v-model="form.machineId" placeholder="请输入设备ID" style="width: 150px;"/>
                                </el-form-item>
                                <el-form-item label="S_1/4分位" prop="sQuarter">
                                  <!-- SEOptions -->
                                  <el-select v-model="form.sQuarter" placeholder="请选择S_1/4分位" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.sQuarter" placeholder="请输入S_1/4分位" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="S_中位数" prop="sMedian">
                                  <el-select v-model="form.sMedian" placeholder="请选择S_中位数" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.sMedian" placeholder="请输入S_中位数" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="S_平均数" prop="sAverage">
                                  <el-select v-model="form.sAverage" placeholder="请选择S_平均数" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.sAverage" placeholder="请输入S_平均数" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="S_众数" prop="sMode">
                                  <el-select v-model="form.sMode" placeholder="请选择S_众数" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.sMode" placeholder="请输入S_众数" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="E_1/4分位" prop="eQuarter">
                                  <el-select v-model="form.eQuarter" placeholder="请选择E_1/4分位" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.eQuarter" placeholder="请输入E_1/4分位" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="E_中位数" prop="eMedian">
                                  <el-select v-model="form.eMedian" placeholder="请选择E_中位数" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.eMedian" placeholder="请输入E_中位数" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="E_平均数" prop="eAverage">
                                  <el-select v-model="form.eAverage" placeholder="请选择E_平均数" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.eAverage" placeholder="请输入E_平均数" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="E_众数" prop="eMode">
                                  <el-select v-model="form.eMode" placeholder="请选择E_众数" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in SEOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                    <!-- <el-input v-model="form.eMode" placeholder="请输入E_众数" style="width: 150px;"/> -->
                                </el-form-item>
                                <el-form-item label="连续天数" prop="daysParameter">
                                    <el-input-number controls-position="right" v-model="form.daysParameter" placeholder="请输入连续天数" style="width: 150px;"/>
                                </el-form-item>
                                <el-form-item label="ST类型" prop="stType">
                                    <!-- <el-input controls-position="right" v-model="form.stType" placeholder="请输入置信区间" style="width: 150px;"/> -->
                                    <el-select v-model="form.stType" placeholder="请选择ST类型" clearable style="width: 150px;">
                                        <el-option
                                            v-for="dict in stTypeOptions"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="ATT下限" prop="attLl">
                                    <el-input-number controls-position="right" v-model="form.attLl" placeholder="请输入ATT下限" style="width: 150px;"/>
                                </el-form-item>
                                <el-form-item label="ATT上限" prop="attUl">
                                    <el-input-number controls-position="right" v-model="form.attUl" placeholder="请输入ATT上限" style="width: 150px;"/>
                                </el-form-item>
                                <el-form-item label="取样数Min" prop="sampleSize">
                                    <el-input v-model="form.sampleSize" placeholder="请输入取样数Min" style="width: 150px;"/>
                                </el-form-item>
                                <el-form-item label="ST源Unit1" prop="source1">
                                    <el-input v-model="form.source1" placeholder="请输入ST源Unit1" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="ST源Unit2" prop="source2">
                                    <el-input v-model="form.source2" placeholder="请输入ST源Unit2" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="ST源Unit3" prop="source3">
                                    <el-input v-model="form.source3" placeholder="请输入ST源Unit3" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="ST源Unit4" prop="source4">
                                    <el-input v-model="form.source4" placeholder="请输入ST源Unit4" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="ST源Unit5" prop="source5">
                                    <el-input v-model="form.source5" placeholder="请输入ST源Unit5" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="腔体数" prop="chCnt">
                                    <el-input v-model="form.chCnt" placeholder="请输入腔体数" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="ST重算" prop="stUpDown">
                                    <!-- <el-input v-model="form.stUpDown" placeholder="请输入ST重算" style="width: 150px;" /> -->
                                    <el-select v-model="form.stUpDown" placeholder="请选择车间" clearable style="width: 150px;">
                                        <el-option
                                                v-for="dict in stUpDownOptions"
                                                :key="dict.value"
                                                :label="dict.label"
                                                :value="dict.value"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" style="width: 405px;" />
                                </el-form-item>
                                <!-- <el-form-item label="创建人" prop="createUser">
                                    <el-input v-model="form.createUser" placeholder="请输入创建人" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item label="更新人" prop="updateUser">
                                    <el-input v-model="form.updateUser" placeholder="请输入更新人" style="width: 150px;" />
                                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="StInfo">
  import { listStInfo, getStInfo, delStInfo, addStInfo, updateStInfo } from "@/api/funConfig/stInfo"
  // options
  import { factoryIdOptions, factoryAreaIdOptions, listProductionTypeOptions, listMachineTypeOptions } from '@/common/options'
  // 级联
  import { getMachineTypeId, getModelType } from '@/common/affect'
  import useUserStore from '@/store/modules/user'

  import { column } from './config'

  column.forEach((item) => {
    item.filter = 'agMultiColumnFilter'
  })

  const { proxy } = getCurrentInstance()

  const tableData = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")

  const gridApi = ref()

  const height = ref('calc(100% - 100px)')

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 1000,
      factoryId: null,
      factoryAreaId: null,
      productionTypeId: null,
      machineTypeId: null,
      machineId: null
    },
    rules: {
    }
  })

  const stUpDownOptions = ref([{
    label: 'null', value: ''
  }, {
    label: 'Up', value: 'Up'
  }, {
    label: 'Down', value: 'Down'
  }])

  const SEOptions = [
    { label: 0, value: 0 },
    { label: 1, value: 1 }
  ]

  const stTypeOptions = [
    { label: 'AST', value: 'AST' },
    { label: 'MST', value: 'MST' }
  ]

  const selectionChanged = (params) => {
    gridApi.value = params.api
    const selectedRows = params.api.getSelectedRows()
    single.value = selectedRows.length !== 1
    multiple.value = !selectedRows.length
  }

  const { queryParams, form, rules } = toRefs(data)

  /** 查询AST_ST基准情报列表 */
  function getList() {
    loading.value = true
    listStInfo(queryParams.value).then(response => {
      tableData.value = response.rows
      // height.value = `${(response.rows.length * 32) + 40}px`
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      siteId: null,
      factoryId: null,
      factoryAreaId: null,
      lineid: null,
      productionTypeId: null,
      subProductionTypeId: null,
      machineTypeId: null,
      stdGroup: null,
      machineId: null,
      stType: null,
      sQuarter: null,
      sMedian: null,
      sAverage: null,
      sMode: null,
      eQuarter: null,
      eMedian: null,
      eAverage: null,
      eMode: null,
      daysParameter: null,
      ciParameter: 2,
      attLl: null,
      attUl: null,
      stepFigure: null,
      productFigure: null,
      sampleSize: null,
      source1: null,
      source2: null,
      source3: null,
      source4: null,
      source5: null,
      chCnt: null,
      stUpDown: null,
      movingType: null,
      maker: null,
      group: null,
      applyDate: null,
      remark: null,
      mouduleType: null,
      createUser: null,
      createTime: null,
      updateUser: null,
      updateTime: null
    }
    proxy.resetForm("stInfoRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加AST_ST基准情报"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _machineId = gridApi.value.getSelectedRows()[0].machineId
    getStInfo(_machineId).then(response => {
      form.value = response.data
      open.value = true
      title.value = "修改AST_ST基准情报"
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["stInfoRef"].validate(valid => {
      if (valid) {

        const _target = [
          form.value.sQuarter,
          form.value.sMedian,
          form.value.sAverage,
          form.value.sMode,
          form.value.eQuarter,
          form.value.eMedian,
          form.value.eAverage,
          form.value.eMode
        ].filter(item => item === 1)
        if (title.value.includes('修改')) {
          if(_target.length !== 1){
            proxy.$modal.alertError(`flag选择不正确 请重新选择!`)
            return
          }
          form.value.updateUser = useUserStore().name
          updateStInfo(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          form.value.createUser = useUserStore().name
          if(_target.length !== 1){
            proxy.$modal.alertError(`flag选择不正确 请重新选择!`)
            return
          }
          addStInfo(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _machineIds = []
    gridApi.value.getSelectedRows().map(item => _machineIds.push(item.machineId) )
    proxy.$modal.confirm('是否确认删除AST_ST基准情报编号为"' + _machineIds + '"的数据项？').then(function() {
      return delStInfo(_machineIds)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('funConfig/stInfo/export', {
      ...queryParams.value
    }, `stInfo_${new Date().getTime()}.xlsx`)
  }

  /**
   * 级联
   *
   * 制造类型
   */
  const areaChange = (target) => {
    queryParams.value.productionTypeId = null
    queryParams.value.machineTypeId = null
    listProductionTypeOptions.value = []
    if(!target.length) return
    getModelType({
      factoryAreaIdList: queryParams.value.factoryAreaId
    }).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  /**
   * 级联
   *
   * 设备类型
   */
  const productionTypeIdChange = (target) => {
    queryParams.value.machineTypeId = null
    listMachineTypeOptions.value = []
    if(!target.length) return
    getMachineTypeId({
      productionTypeIdList: queryParams.value.productionTypeId,
      isMainmachineType: 'N' // 固定参数（必传）
    }).then((res) => {
      res.rows.forEach(item => {
        listMachineTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  getList()
</script>
